package com.leetcode.array;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 先排序，然后就是towSum的解法类似，采用双指针  - >  [0,0,0,0] 用例没通过
 */
public class Leetcode15 {

    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> sumList = new ArrayList<>();
        if (nums.length < 3) {
            return sumList;
        }
        Arrays.sort(nums);
        for (int i = 0 ; i < nums.length ; i++) {
            // 当前都大于0 ，则其和肯定大于0
            if (nums[i] > 0)
                break;
            // 去除重复
            if (i > 0 && nums[i] == nums[i-1])
                continue;
            int left = i+1; // 左指针
            int right = nums.length-1; //右指针
            while (left < right) {
                    int sum = nums[i] + nums[left] + nums[right];
                    if (sum < 0) {
                        left++;
                    } else if (sum > 0) {
                        right--;
                    } else {
                        List<Integer> list = new ArrayList<>();
                        // 要考虑去除重复
                        while (left < right && nums[left] == nums[left + 1 ])
                            left++;
                        while (left < right && nums[right] == nums[right - 1])
                            right--;
                        list.add(nums[i]);
                        list.add(nums[left]);
                        list.add(nums[right]);
                        sumList.add(list);
                        left++;
                        right--;
                    }

            }
        }
        return sumList;
    }

    public static void main(String[] args) {
        int[] arr = {-1,0,1,2,-1,-4};
        Leetcode15 leet = new Leetcode15();
        leet.threeSum(arr);
    }

}
